package cascade.controller.pages.commands
{
	
	import cascade.App;
	import cascade.model.Page;
	import cascade.view.pages.NewPageDialog;
	
	import flight.commands.AsyncCommand;
	import flight.net.RemoteService;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.Fault;

	public class CommandCreatePage extends AsyncCommand
	{
		public var parent:Page;
		
		
		public override function execute():*
		{
			var newPageDialog:NewPageDialog = new NewPageDialog();
			newPageDialog.parentPage = Cascade.view.selectedPage;
			newPageDialog.callback = onDialogSubmit;
			newPageDialog.open();
		}
		
		
		protected function onDialogSubmit(dialog:NewPageDialog):void
		{
			Cascade.busy.addBusy(this);
			
			parent = dialog.parentPage;
			
			Cascade.service.SiteService.createPage(dialog.pageName, dialog.pageTitle, parent.id, result, fault);
		}
		
		
		protected function result(page:Page):void
		{
			
			// add the page to the pages array after the parent
			var index:Number;
			var children:ArrayCollection = parent.parent ? parent.parent.children : Cascade.model.siteTree;
			var parentIndex:Number = children.getItemIndex(parent);
			index = parentIndex + 1;
			Cascade.model.pages.addItemAt(page, index);
			
			// add the page to the parent's children array
			page.parent = parent;
			if (!parent.children)
				parent.children = new ArrayCollection();
			parent.children.addItemAt(page, 0);
			
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
		
		protected function fault(info:Object):void
		{
			trace(info);
			Cascade.busy.removeBusy(this);
		}
	}
}